package edu.washington.ling.syntric.consistency;

import edu.washington.ling.syntric.struct.tree.Token;
import edu.washington.ling.syntric.struct.tree.Tree;

public class PassiveRule extends ConsistencyRule {
	@Override
	public void apply(Tree ds) {
		Token dsRoot = ds.getDSRoot();
		apply(dsRoot, ds);
	}

	public void apply(Token t, Tree ds) {
		for (Token child: t.getDSDependents()) {
			apply(child, ds);
		}
		Token k1Child = null;
		Token k2Child = null;
		Token pofChild = null;
		for (Token child: t.getDSDependents()) {
			if (child.getDSRelation().equals("k1")) {
				k1Child = child;
			}
			if (child.getDSRelation().equals("k2")) {
				k2Child = child;
			}
			if (child.getDSRelation().equals("pof")) {
				pofChild = child;
			}
		}
		for (Token child: t.getECDependents()) {
			if (child.getDSRelation().equals("k2")) {
				k2Child = child;
			}
		}
		
		// Diagnostic test
		if (t.hasFeature("voicetype") && t.getTag().equals("VM")) {
			// Diagnostic test
			if (t.getValue("voicetype").equals("passive") && 
					(k2Child != null || (pofChild != null && k2Child == null))) {
				t.setFeature("passive", Boolean.toString(true));
				
				// Operation					
			
				// Get index for new EC
				int index = ds.nextCoindex();
			
				// Create a CASE ec and attach
				// to t with k2 relation
				Token ec = ConsistencyUtils.createMovementEC("CASE", "k2", index);
	
				// Add ec to t 
				t.addECDependent(ec);
				
				if (k2Child != null) {
					// Map relation of k2-child to k1
					k2Child.setDSRelation("k1");
					// Set target coindex of k1- (formerly k2-) child
					k2Child.setDSTargetIndex(index);
				} else if (pofChild != null) {
					// Set target coindex of pof-child 
					pofChild.setDSTargetIndex(index);
				}
				if (k1Child != null) {
					// If agent exists, set its relation to k1-passive
					k1Child.setDSRelation("k1-passive");
				}
			}
		}
	}
}
